/**
 * the background Service that process the message sending by sendMyMessage()
 * and coming message by newMsgArrive()
 * <p>
 * it also manage the message queue for ChatActivity
 */

package com.tjian.fafa.user.base.chatServices;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;

import com.tjian.fafa.user.base.ConnectedApp;
import com.tjian.fafa.user.base.bean.ChatEntity;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.chatter.ChatActivity;
import com.tjian.fafa.user.base.commons.GlobalMsgTypes;
import com.tjian.fafa.user.base.mainBody.MainBodyActivity;
import com.tjian.fafa.user.base.mainBody.MainTabMsgPage;
import com.tjian.fafa.user.base.myNetwork.NetworkService;
import com.tjian.fafa.user.base.util.UnsavedChatMsg;
import com.tjian.util.TypeUtil;

import java.util.List;

public class ChatService extends Service
{

    private static ChatService ChatServiceInstance;

    private ChatActivity chatActivity = null;
    private ChatMsgReceiver chatMsgReceiver = null;
    private ChatBinder chatBinder = new ChatBinder();

    private int curType = 0; // 0 for public room (default), 1 for group room, 2 for friend chatting

    private UserInfo userInfo;
    private int friendId;
    private String imgPath;
    private boolean mEnterFromNotification;
    private int mEnterFromNotificationId;

    public static ChatService getInstance()
    {
        return ChatServiceInstance;
    }

    public class ChatBinder extends Binder
    {
        public ChatService getService()
        {
            return ChatService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return chatBinder;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        friendId = -1;
        ChatServiceInstance = this;
        IntentFilter intentFilter = new IntentFilter("fafa.example.hello.MESSAGE_RECEIVED");
        chatMsgReceiver = new ChatMsgReceiver(this);
        ChatService.this.registerReceiver(chatMsgReceiver, intentFilter);
        userInfo = ConnectedApp.getInstance().getUserInfo();
        //System.out.println("==========,_20170101_100056,\n" + TypeUtil.typeToString("123", 123));
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        ChatService.this.unregisterReceiver(chatMsgReceiver);
        NetworkService.getInstance().closeConnection();
        ChatServiceInstance = null;
    }

    public boolean getEnterFromNotification()
    {
        return mEnterFromNotification;
    }

    public void setEnterFromNotification(boolean b)
    {
        mEnterFromNotification = b;
    }

    public int getEnterFromNotificationId()
    {
        return mEnterFromNotificationId;
    }

    public void setEnterFromNotificationId(int id)
    {
        mEnterFromNotificationId = id;
    }

    public void setBoundChatActivity(ChatActivity act0)
    {
        chatActivity = act0;
    }

    public void setType(int type)
    {
        curType = type;
    }

    public void setId(int id)
    {
        friendId = id;
    }

    public int getId()
    {
        return friendId;
    }

    public String getmImgpath()
    {
        return imgPath;
    }

    public void setmImgpath(String imgPath)
    {
        this.imgPath = imgPath;
    }

    public void sendMyMessage(String message)
    {
        if (curType == GlobalMsgTypes.msgFromFriend) //类型为2
        {
            ChatEntity chatEntity = new ChatEntity(curType, userInfo, friendId, message, imgPath);
            NetworkService.getInstance().sendUpload(curType, chatEntity.toString());
            newMsgArrive(chatEntity.toString(), true);
        }
    }

    public void newMsgArrive(String newMsg, boolean isSelf)
    {

        ChatEntity chatEntity = new ChatEntity(newMsg);
        int type = chatEntity.getType();
        // id is the id of the one client is talking to, regardless of him/her being sender or receiver
        int id = chatEntity.getSenderId();
        if (isSelf)
        {
            id = friendId;
        }
        ChatServiceData.getInstance().getCurMsg(type, id).add(chatEntity);
        ChatServiceData.getInstance().getCurIsSelf(type, id).add(isSelf);
        chatActivityDisplayHistory();
        String imgpath = "";
        UnsavedChatMsg.getInstance().newMsg(type, id, chatEntity, isSelf);

        if (!ChatActivity.getIsActive() || friendId != id)
        {
            ChatServiceData.getInstance().increUnreadMsgs(id);
        }
        imgpath = chatEntity.getmAvatarImagePath();
        if (!ChatActivity.getIsActive() || friendId != id)  //对方头像
        {
            MainTabMsgPage.getInstance().onUpdateByUserinfo(FriendListInfo.getFriendListInfo().getUserFromId(id),
                    chatEntity.getContent(), chatEntity.getTime(), true, imgpath); //chatEntity.getmAvatarImagePath()
        }
        else
        {
            MainTabMsgPage.getInstance().onUpdateByUserinfo(FriendListInfo.getFriendListInfo().getUserFromId(id),
                    chatEntity.getContent(), chatEntity.getTime(), false, imgPath); //chatEntity.getmAvatarImagePath()
        }

        if (MainBodyActivity.getCurPage() == MainBodyActivity.mPageMsg)
        {
            MainTabMsgPage.getInstance().onUpdateView();
        }
    }

    public void chatActivityDisplayHistory()
    {
        if (chatActivity == null)
        {
            return;
        }
        if (ChatActivity.getIsActive())
        {
            List<ChatEntity> chatEntityList = ChatServiceData.getInstance().getCurMsg(curType, friendId);
            List<Boolean> isSelf = ChatServiceData.getInstance().getCurIsSelf(curType, friendId);

            if (curType == GlobalMsgTypes.msgFromFriend)
            {
                chatActivity.updateListviewHistory(chatEntityList, isSelf, curType, FriendListInfo.getFriendListInfo().
                        getNameFromId(friendId));
            }
        }
    }

}
